package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TanhuaService {
    //注入api
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private UserLocationApi userLocationApi;

    //查询今日佳人
    public TodayBest todayBest() {
        //1.获取到当前用户id
        Long toUserId = UserHolder.getUserId();
        //2.根据当前用户id查询出缘分值最高的
        RecommendUser user = recommendUserApi.findMaxScore(toUserId);
        //3.针对 新用户没有推荐的
        if (user == null) {
            //构造默认推荐数据
            user = new RecommendUser();
            user.setToUserId(toUserId);
            user.setUserId(1l);
            user.setScore(95d);
        }
        //4.TodayUser根据userId查询需要推荐用户的信息
        UserInfo userInfo = userInfoApi.findById(user.getUserId());
        //5.将RecommentUser 转化为TodayBest
        return TodayBest.init(userInfo, user);
    }

    //查询首页推荐好友
    public PageResult recommendation(Integer page, Integer pagesize) {
        //1.获取当前用户id,查询条件
        Long toUserId = UserHolder.getUserId();
        //2.调用api,根据分页条件和用户id查询出列表
        List<RecommendUser> list = recommendUserApi.findRecommendationList(toUserId, page, pagesize);
        if (CollUtil.isEmpty(list)) {
            //3.对于新用户没有推荐数据,就需要给出默认的推荐数据
            list = defaultList();
        }
        //4.因为前端返回的要求是vo对象,所以需要将返回的List集合转换成对应的vo对象来进行返回
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : list) {
            //得到用户id,根据用户id查询对应的用户信息
            UserInfo userInfo = userInfoApi.findById(user.getUserId());
            TodayBest vo = TodayBest.init(userInfo, user);
            //将得到的记过添加到集合当中
            vos.add(vo);
        }
        //5.将vo对象合并到PageResult当中;
        return new PageResult(page, pagesize, 0l, vos);
    }

    //默认返回的推荐数据列表
    private List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        //构造默认推荐数据，企业中按照项目经理要求
        for (int i = 1; i <= 10; i++) {
            RecommendUser ru = new RecommendUser();
            ru.setUserId((long) i); //模拟推荐的用户id
            ru.setScore(95D); //模拟推荐的评分
            list.add(ru);
        }
        return list;
    }

    //查询好友信息和动态
    public TodayBest personalInfo(Long userId) {
        //1.当前知道要查询的用U户id
        //2.获取到被推荐人的id
        Long toUserId = UserHolder.getUserId();
        UserInfo info = userInfoApi.findById(userId);
        RecommendUser user = recommendUserApi.find(userId, toUserId);
        //3.构建出TodayBest对象
        return TodayBest.init(info, user);
    }

    //查看陌生人问题
    public String strangerQuestions(Long userId) {
        //通过调用questionApi的方法来查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        //这里使用三元表达式来进行判断，如果问题为空就自定义返回
        return question == null ? "你喜欢java吗？" : question.getTxt();
    }

    //回复陌生人问题
    public void reply(Long userId, String reply) {
        //这里主要就是实现一条系统消息的发送（好友验证）
        //发送内容是一个字符串
        Map map = new HashMap();
        map.put("userId", UserHolder.getUserId());
        map.put("huanXinId", "hx" + UserHolder.getUserId());//错的都一样
        UserInfo user = userInfoApi.findById(UserHolder.getUserId());
        map.put("nickname", user.getNickname());
        map.put("strangerQuestion", strangerQuestions(userId));
        map.put("reply", reply);
        //将map集合转换为JSON字符串
        String json = JSON.toJSONString(map);
        huanXinTemplate.sendMsg("hx" + userId, json);
    }

    //搜索附近的人
    public List<NearUserVo> search(String gender, String distance) {
        //需要查询到用户位置
        //1.获取到当前用户id
        Long userId = UserHolder.getUserId();
        List<Long> ids = userLocationApi.findIds(userId, distance);
        //2.根据ids查询出用户信息
        Map<Long, UserInfo> infos = userInfoApi.findByIds(ids);
        //3.进行循环一个info构建一个vo对象
        List<NearUserVo> vos = new ArrayList<>();
        for (Long id : ids) {
            if (userId == id) {
                continue;//跳出本次循环
            }
            UserInfo info = infos.get(id);
            if (!info.getGender().equals(gender)) {
                continue;
            }
            NearUserVo vo = NearUserVo.init(info);
            vos.add(vo);
        }
        //返回vo集合
        return vos;
    }

}
